/**
 * Copyright 2013-2015
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */	  

package com.cos.controller.app.company;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cos.controller.base.BaseController;
import com.cos.service.admin.dynamic.CompanyCircleService;
import com.cos.service.admin.dynamic.DynamicImgService;
import com.cos.service.information.pictures.PicturesService;
import com.cos.service.interfaces.InsertCompanyService;
import com.cos.service.interfaces.IntCompanyService;
import com.cos.service.interfaces.role.IntMenuService;
import com.cos.service.system.appuser.AppuserService;
import com.cos.util.AppUtil;
import com.cos.util.Const;
import com.cos.util.DateUtil;
import com.cos.util.FileUpload;
import com.cos.util.Jurisdiction;
import com.cos.util.MapDistance;
import com.cos.util.PageData;
import com.cos.util.PathUtil;
import com.cos.util.ResponseUtil;
import com.cos.util.StringUtil;
import com.cos.util.Tools;
import com.cos.util.Watermark;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * TODO 类或接口说明
 * <p/>
 * 
 * @author <a href="15083378620@163.com">LXJ</a>
 * @version  Date: 2016年3月28日 上午9:28:31
 * @serial 1.0
 * @since 2016年3月28日 上午9:28:31
 */
@Controller
@RequestMapping(value="/appuser")
public class IntCompanyController extends BaseController{
	
	@Resource(name="insertCompanyService")
	private InsertCompanyService insertCompanyService;
	@Resource(name="appuserService")
	private AppuserService appuserService; 
	@Resource(name="picturesService")
	private PicturesService picturesService;
	@Resource
	private IntMenuService intMenuService;
	@Resource(name="companyCircleService")
	private CompanyCircleService companyCircleService;
	@Resource(name="intCompanyService")
	private IntCompanyService intCompanyService;
	@Resource(name="dynamicImgService")
	private DynamicImgService dynamicImgService;
	
	/*
	 * 申请创建团队
	 * 
	 */
	@RequestMapping(value="/saveCompany")
	@ResponseBody
	public Object saveCompany(HttpServletRequest request) throws Exception{
		logBefore(logger, "创建团队");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("getCompany", pd)){
				pd.put("ID", this.get32UUID());	//公司表主键
				insertCompanyService.save(pd);//保存公司基本信息
				String ID = (String) pd.get("ID");
				pd.put("U_C_ID", this.get32UUID());//用户和公司表中间表主键
				pd.put("ROLE_ID", 1);//创建人默认是企业管理员
				pd.put("D_ID", 0);//默认增加一个部门就是 公司部
				insertCompanyService.save_user_Company(pd);//保存到用户公司中间表
				pd = insertCompanyService.selectUserInfo(pd);//检索出用户在sys_app_user基本信息 
				pd.put("USER_ID", this.get32UUID());
				pd.put("STATUS",0);
				insertCompanyService.savetUserInfo(pd);//将用户的基本信息添加到sys_user 表中，使用户可以登录
				List <PageData> menuList = intMenuService.getCompanyMenu(pd);//初始化公司菜单
				pd.put("STATUS", 1);
				for(int i=0;i<menuList.size();i++){
					 pd.put("AID",this.get32UUID());//中间表的主键
					 pd.put("MENU_ID", menuList.get(i).getString("MENU_ID"));
					 intMenuService.insertCompanyMenu(pd);
				 }
				map.put("ID",ID);
				result = (null == pd) ? "02" : "01";
			}
			else{
				result = "03";
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return  AppUtil.returnObject(new PageData(), map);
	}
	
	/*
	 * 更新团队Logo
	 */
	@RequestMapping(value="/updateCompany")
	@ResponseBody
	public Object updateCompany(
			@RequestParam(required=false) MultipartFile file
			) throws Exception{
		logBefore(logger, "更新公司Logo");
		Map<String,String> map = new HashMap<String,String>();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			//if(AppUtil.checkParam("getDepartment", pd)){
			String  ffile = DateUtil.getDays(), fileName = "";
			insertCompanyService.update(pd);
			if (null != file && !file.isEmpty()) {
				String filePath = PathUtil.getClasspath() + Const.FILEPATHIMG + ffile;		//文件上传路径
				fileName = FileUpload.fileUp(file, filePath, this.get32UUID());				//执行上传
			}else{
				System.out.println("上传失败");
			}
			pd.put("PICTURES_ID", this.get32UUID());
			pd.put("PATH", ffile + "/" + fileName);
			pd.put("CREATETIME", Tools.date2Str(new Date()));
			Watermark.setWatemark(PathUtil.getClasspath() + Const.FILEPATHIMG + ffile + "/" + fileName);
			picturesService.saveAPP(pd);
			map.put("result", "ok");
			//}
		}catch (Exception e) {
			logger.error(e.toString(), e);
		}finally {
			logAfter(logger);
		}
		
		return AppUtil.returnObject(pd, map);
	}
	
	
	/**
	 * 获取功能定制
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/selectDeparment")
	@ResponseBody
	public Object selectDeparment(HttpServletResponse response) throws Exception{
		logBefore(logger, "获取功能定制");
		PageData pd = new PageData();
		JSONObject workDeparment = new JSONObject();
		pd = this.getPageData();
		String result = "00";
		try {
			if(AppUtil.checkParam("getDepartment", pd)){
				List<PageData> deparmentList = new ArrayList<PageData>();
				deparmentList = insertCompanyService.getDeparment(pd);//获取功能定制
				JSONArray rows = JSONArray.fromObject(deparmentList);//将list集合转换为json数组
				result = (null == deparmentList) ?  "02" :  "01";
				workDeparment.put("rows", rows);//将json数组转换为json对象
			}
		}catch (Exception e) {
			logger.error(e.toString(), e);
		}finally{
			workDeparment.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, workDeparment);
		return null;
	}
	
	
	/**
	 * 插入功能定制
	 * @param response
	 * @return
	 * @throws Exception
	 */
	
	@RequestMapping(value="/save_APP_Menu")
	@ResponseBody
	public Object Save_APP_Menu(HttpServletRequest request)throws Exception{
		logBefore(logger, "添加功能");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("saveAppMenu", pd)){
				pd.put("STATUS", 1);//更新菜单状态为1
				pd.put("ID", this.get32UUID());
				insertCompanyService.update(pd);//更新菜单状态为1保存到数据库
				insertCompanyService.saveAppMenu(pd);//将添加的功能保存到数据库
				result = (null == pd) ? "02" : "01";
			}
			else{
				result = "03";
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return  AppUtil.returnObject(new PageData(), map);
	}
	
	
	
	/*
	 * 更新团队名称
	 */
	@RequestMapping(value="/updateCName")
	@ResponseBody
	public Object update_CName(HttpServletResponse response) throws Exception{
		logBefore(logger, "更新公司名称");
		Map<String,String> map = new HashMap<String,String>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if(AppUtil.checkParam("getCName", pd)){//检查参数
				insertCompanyService.UpdateCName(pd);//更新公司名称
				result = (null == pd) ? "02" : "01";
			}
			else{
				result = "03";
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);//将结果集放入map中
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}
	
	/**
	 * 查找公司
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/searchCompany")
	@ResponseBody
	public Object searchCompany(HttpServletResponse response) throws Exception{
		PageData pd = new PageData();
		JSONObject company = new JSONObject();
		pd = this.getPageData();
		String result = "00";
		try{
			//if(AppUtil.checkParam("searchCompany", pd)){	//检查参数
				List<PageData> companyList = new ArrayList<PageData>();
				pd.put("NAME", StringUtil.formatLike(pd.getString("NAME")));
				companyList = insertCompanyService.searchCompany(pd);
				JSONArray rows = JSONArray.fromObject(companyList);
				result = "02";
				company.put("rows", rows);
		/*	}else{
				result = "03";
			}*/
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			company.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, company);
		return null;
	}
	
	
	/**
	 * 会员加入公司
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/joinCompany")
	@ResponseBody
	public Object joinCompany(HttpServletResponse response) throws Exception{
		PageData pd = new PageData();
		JSONObject company = new JSONObject();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("joinCompany", pd)){	//检查参数
				pd.put("ID", this.get32UUID());
				pd.put("STATUS", 1);
				pd.put("D_ID", 0);
				pd.put("ROLE_ID", 4);
				insertCompanyService.joinCompany(pd);
				result = "02";
			}else{
				result = "03";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			company.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, company);
		return null;
	}
	
	/**
	 * 创建团组
	 * @param response  D_ID C_ID NAME
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/saveDepartment")
	@ResponseBody
	public Object saveDepartment(HttpServletResponse response) throws Exception{
		PageData pd = new PageData();
		JSONObject company = new JSONObject();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("saveDepartment", pd)){	//检查参数
				pd.put("ID", this.get32UUID());
				pd.put("STATUS", 1);
				pd.put("PARENT_ID", 0);
				insertCompanyService.saveDepartment(pd);
				insertCompanyService.saveUserDepartment(pd);
				company.put("ID", pd.get("ID"));
				result = "02";
			}else{
				result = "03";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			
			company.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, company);
		return null;
	}
	
	/**
	 * 创建子类部门
	 * @param response  D_ID C_ID NAME
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/saveSonDepartment")
	@ResponseBody
	public Object saveSonDepartment(HttpServletResponse response) throws Exception{
		PageData pd = new PageData();
		JSONObject company = new JSONObject();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("saveSonDepartment", pd)){	//检查参数
				pd.put("ID", this.get32UUID());
				pd.put("STATUS", 1);
				insertCompanyService.saveDepartment(pd);
				insertCompanyService.saveUserDepartment(pd);
				result = "02";
			}else{
				result = "03";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			
			company.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, company);
		return null;
	}
	
	/**
	 * 获取公司下的员工
	 * @param response   C_ID 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getUserByCompany")
	@ResponseBody
	public Object getUserByCompany(HttpServletResponse response) throws Exception{
		PageData pd = new PageData();
		JSONObject company = new JSONObject();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("getDepartment", pd)){	//检查参数
				List<PageData> userList = new ArrayList<PageData>();
				userList = insertCompanyService.getUserByCompany(pd);
				JSONArray rows = JSONArray.fromObject(userList);
				company.put("rows", rows);
				result = "02";
			}else{
				result = "03";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			company.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, company);
		return null;
	}
	
	/**
	 * 公司将员工加入部门
	 * @param response   D_ID  UIDS C_ID
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/joinDepartment")
	@ResponseBody
	public Object joinDepartment(HttpServletResponse response) throws Exception{
		PageData pd = new PageData();
		JSONObject company = new JSONObject();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("joinDepartment", pd)){	//检查参数
				String []UIDS=pd.getString("UIDS").split(",");
				pd.put("ID", this.get32UUID());
				pd.put("STATUS", 1);
				pd.put("ROLE_ID", 4);
				for(int i=0;i<UIDS.length;i++){
					pd.put("U_ID", UIDS[i]);
					insertCompanyService.joinDepartment(pd);
				}
				result = "02";
			}else{
				result = "03";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			company.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, company);
		return null;
	}
	
	
	/**
	 * 附近企业查询
	 * @param response   D_ID  UIDS C_ID
	 * @return
	 * @throws Exception
	 */
		@SuppressWarnings("static-access")
		@RequestMapping(value="/selectAttachment")
		@ResponseBody
		public Object selectAttachment(HttpServletResponse response) throws Exception{
			PageData pd = new PageData();
			JSONObject company = new JSONObject();
			pd = this.getPageData();
			String result = "00";
			List<PageData> pa = new ArrayList<PageData>() ;
			try{
				if(AppUtil.checkParam("selectAttachment", pd)){	//检查参数
					String LONGITUDE  = (String)pd.get("LONGITUDE");//经度  
					String LATITUDE  = (String)pd.get("LATITUDE");// 纬度  
					int RAD = Integer.parseInt((String)pd.get("RAD"));// 半径
					List<PageData> listCompany = new ArrayList<PageData>();
					listCompany  = insertCompanyService.selectAttachment(pd);
					for(int i = 0;i<listCompany.size();i++){
						PageData pc = new PageData() ;
						if(listCompany.get(i).get("LONGITUDE").toString()!=null && listCompany.get(i).get("LATITUDE").toString()!=null){
					        String C_LONGITUDE = listCompany.get(i).get("LONGITUDE").toString();
							String C_LATITUDE = listCompany.get(i).get("LATITUDE").toString();
							String C_ID = listCompany.get(i).get("ID").toString();
							MapDistance mapDistance = new MapDistance();
							int length = Integer.valueOf(mapDistance.getDistance(LONGITUDE,LATITUDE,C_LONGITUDE,C_LATITUDE)).intValue();
							if(length<RAD){
								pc.put("LONGITUDE", C_LONGITUDE);
								pc.put("LATITUDE", C_LATITUDE);
								pc.put("C_ID", C_ID);
								pa.add(pc);
							}
						}	}
						JSONArray rows = JSONArray.fromObject(pa);
						company.put("rows", rows);
						result = "02";
					}else{
						result = "03";
					}
				} catch (Exception e) {
					logger.error(e.toString(), e);
				}finally {
					company.put("result", result);
					logAfter(logger);
				}
				ResponseUtil.write(response, company);
				return null;
		}
		
		/**
		 * 根据用户id查平台信息分类和企业自定义信息分类
		 * @return
		 * @throws Exception
		 */
		@RequestMapping(value="/getInfoCatByUID")
		@ResponseBody
		public Object getInfoCatByUID(HttpServletResponse response) throws Exception{
			PageData pd = new PageData();
			pd = this.getPageData();
			PageData pds = new PageData();
			List<PageData> p = appuserService.getCompany(pd) ;
			if(p.size()>0) {
				String cid = appuserService.getCompany(pd).get(0).getString("ID") ;//获取公司的id
				pd.put("C_ID", cid) ;
				List<PageData> rows = intCompanyService.getCats(pds) ;
				pds.put("C_ID", cid) ;
				pds.put("rows", rows) ;
				pds.put("result", "success") ;
				return pds;
			} else {
				pds.put("result", "error") ;
				return pds ;
			}
		}
		
		/**
		 * 返回需要保存图片的路径
		 * @return
		 * @throws Exception
		 */
		@RequestMapping(value="/uploadCompNewsPic")
		@ResponseBody
		public Object uploadCompNewsPic(@RequestParam(required=false) MultipartFile[] file,HttpServletResponse response) throws Exception{
			List<PageData> pds = new ArrayList<PageData>() ;
			PageData pdss = new PageData() ;
			String  ffile = DateUtil.getDays(), fileName = "";
			if (null != file && file.length != 0) {
				int type_id = 0 ;
				for(MultipartFile f:file) {
					if(f.getSize() != 0) {
						PageData pd = new PageData();
						//上传路径
						String filePath = PathUtil.getClasspath() + Const.FILEPATHIMG + ffile;		//文件上传路径
						//数据库中保存的文件名（即文件真是名）
						fileName = FileUpload.fileUp(f, filePath, this.get32UUID());	
						pd.put("URL", ffile + "/" + fileName);	//路径
						type_id++;
						pds.add(pd) ;
					}
				}
					pdss.put("TYPE_ID", type_id) ;
					pdss.put("rows",pds) ;
					pdss.put("result", "success") ;
				} else {
					pdss.put("result", "error") ;
				}
			return pdss;
		}
		
		/**
		 * 发布动态
		 * @return
		 * @throws Exception
		 */
		@RequestMapping(value="/saveCompanyNews")
		@ResponseBody
		public Object saveCompanyNews(HttpServletResponse response) throws Exception{
			logBefore(logger, "添加动态");
			PageData pd = new PageData();
			pd = this.getPageData() ;
			Map<String,String> map = new HashMap<String,String>();
			List<PageData> pageDatas = new ArrayList<PageData>() ;
			List<PageData> pageDatass = new ArrayList<PageData>() ;
			String[] newIds =null ;//自定义内容分类的id
			String[] IDS = null ; //获取已经选择的分类
			String[] CI_IDs = null ;
			try{
				String C_ID = pd.getString("c_id") ; //获取企业
				pd = this.getPageData();
				pd.put("C_ID",C_ID ) ;
				List<PageData> newsCats = (List<PageData>) pd.get("newsCats") ; //分类
				List<PageData> imgUrls =  (List<PageData>) pd.get("rows") ;//图片集合
				String TYPE_ID = pd.getString("typeid") ;//照片数量
				String newCompNewsCat = pd.getString("newCompNewsCat") ;//新增企业的分类
				//判断该公司是否自己创建自己的内容分类
				if(newCompNewsCat!=null && !newCompNewsCat.equals("")) {
					String info[] = StringUtil.StrList(newCompNewsCat) ;
					for(int i=0;i<info.length;i++) {
						PageData p = new PageData();
						pd.put("STATUS",1 ) ;
						pd.put("PARENT_ID", 0) ;
						pd.put("NAME", info[i]) ;
						pd.put("ID", this.get32UUID() ) ;
						pageDatas.add(p) ;
						//添加公司自己定义的内容分类
						companyCircleService.saveInformationType(pd);
					}
				}
				//获取已经选择的内容类别
				if(newsCats!=null && newsCats.size()>0) {
					IDS = companyCircleService.groupIDs(newsCats) ;
				}
				//获取自己添加的内容分类
				if(pageDatas.size()>0) {
					String[] idss = companyCircleService.groupIDs(pageDatas) ;
					//将两个分类 合并
					newIds = (String[]) ArrayUtils.addAll(IDS, idss) ;
				} else {
					newIds = IDS ;
				}
				//添加数据到中间表company_info_type
				for(int i=0;i<newIds.length;i++) {
					PageData pd_ = new PageData() ;
					pd_.put("ID", this.get32UUID()) ;
					pd_.put("I_ID", newIds[i]) ;
					pd_.put("C_ID", C_ID) ;
					pageDatass.add(pd_) ;
					companyCircleService.saveCompanyInfoType(pd_); 
				}
				//添加动态信息
				String D_ID = this.get32UUID() ;
				pd.put("ID", D_ID) ;
				pd.put("TIME", Tools.date2Str(new Date())) ;
				pd.put("SUPPORT_NUM  ", 0) ;
				pd.put("TRAMPLE_NUM  ", 0) ;
				pd.put("IS_RECOMMEND", 0) ;
				pd.put("TYPE_ID", TYPE_ID) ;
				companyCircleService.saveDynamic(pd);
				//获取刚才添加company_info_type数据的id
				CI_IDs = companyCircleService.groupIDs(pageDatass) ;
				//添加数据到中间表Dynamic_company_info_type
				for(int i=0;i<CI_IDs.length;i++) {
					PageData pd_ = new PageData() ;
					pd_.put("ID", this.get32UUID()) ;
					pd_.put("CI_ID", CI_IDs[i]) ;
					pd_.put("D_ID", D_ID) ;
					pageDatass.add(pd_) ;
					companyCircleService.saveDynamicCompanyInfoType(pd_);
				}
				//添加图片到数据库
				if(imgUrls!=null && imgUrls.size()>0) {
					for(PageData p:imgUrls) {
						pd.put("ID", this.get32UUID());			//主键
						pd.put("C_ID", C_ID);					//公司id
						pd.put("D_ID", D_ID);					//动态id
						pd.put("URL", p.getString("url")) ;
						//保存图片信息
						dynamicImgService.save(pd);
					}
				}
			}catch(Exception e){
				e.printStackTrace();
				logger.error(e.toString()) ;
				map.put("result", "error") ;
				return map;
			}finally{
				logAfter(logger);
			}
			map.put("result", "success") ;
			return AppUtil.returnObject(pd, map);
		}
		
}
